import { Component, OnInit, OnDestroy, ViewChild } from '@angular/core';
import { NotificationService } from 'app/shared/service';
import { Subject } from 'rxjs';
import { PlanMsgInfoComponent } from '../plan-msg-info/plan-msg-info.component';
const domtoimage = require('dom-to-image');

@Component({
    selector: 'itmp-plan-template',
    templateUrl: './plan-template.component.html',
    styleUrls: ['./plan-template.component.css']
})
export class PlanTemplateComponent implements OnInit, OnDestroy {
    @ViewChild(PlanMsgInfoComponent) msgInfo: PlanMsgInfoComponent;

    isLoading = false;
    planImgs = [];
    constructor(private msg: NotificationService) {}

    ngOnInit() {}

    ngOnDestroy() {}

    setDisplayMessage(data) {
        this.msgInfo.setDisplayMessage(data);
    }

    // dom转换成图片
    domtoimage(el, length, sub: Subject<any>) {
        el.style.border = 'none'; // 去除边框
        this.msgInfo.setShowPage(length - 1);
        setTimeout(() => {
            domtoimage
                .toJpeg(el, { cacheBust: true })
                .then(dataUrl => {
                    this.planImgs[this.msgInfo.addService.showPage] = dataUrl.split(',')[1];
                    length--;
                    if (length > 0) {
                        this.domtoimage(el, length, sub);
                    } else {
                        sub.next({
                            planImgs: this.planImgs
                        });
                    }
                })
                .catch(function(error) {
                    console.error('oops, something went wrong!', error);
                });
        }, 200);
    }

    // 判断是否满足条件
    checked() {
        const { category, templatePages } = this.msgInfo.addService.displayMessage;
        // if (!category.categoryId) {
        //     return false;
        // }
        let isOk = true;
        templatePages.forEach(p => {
            if ((p.templateGraphics || []).length !== (p.graphics || []).length) {
                isOk = false;
            }
        });
        return isOk;
    }

    saveClick(sub: Subject<any>) {
        const { templatePages } = this.msgInfo.addService.displayMessage;
        if (!this.checked()) {
            this.msg.notify({ type: 'warning', path: 'DisseminationManagement.MessageLibrary.create_notify' });
            sub.next(false);
            return;
        }
        sub.next(true);
        this.planImgs = [];
        this.domtoimage(this.msgInfo.viewpointRef.nativeElement, templatePages.length, sub);
    }
}
